package club.kittybunny.getjobsysbackend.service;

import club.kittybunny.getjobsysbackend.dao.JobTypeMapper;
import club.kittybunny.getjobsysbackend.entity.JobType;
import club.kittybunny.getjobsysbackend.entity.JobTypeExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: bunny
 * @Description: 我是兔子我会喵，我叫喵星兔
 */
@Service
public class JobTypeService {
    @Autowired
    private JobTypeMapper jobTypeMapper;

    /**
     *
     * @param upperid 父节点主键
     * @param status 是否要求生效状态，如果是false则查询所有，true则查询生效的
     * @return
     * @throws Exception
     */
    public List<JobType> findByUpperid(int upperid, boolean status) throws Exception {
        JobTypeExample e = new JobTypeExample();

        if (status) {
            e.or().andUpperIdEqualTo(upperid).andStatusEqualTo("1");
        } else {
            e.or().andUpperIdEqualTo(upperid);
        }
        List<JobType> list = jobTypeMapper.selectByExample(e);
        return list == null ? new ArrayList<JobType>() : list;
    }

    public int insert(String name, Integer upperId, Integer serno) {
        JobType obj = new JobType();
        obj.setName(name);
        obj.setStatus("1");
        obj.setSerno(serno > 0 ? serno : 1);
        JobType  upper = jobTypeMapper.selectByPrimaryKey(upperId);
        if (upper == null) {
            obj.setLevel(1);
            obj.setUpperId(0);

        } else {
            obj.setLevel(upper.getLevel() + 1);
            obj.setUpperId(upperId);
        }
        int result = jobTypeMapper.insert(obj);
        return obj.getId()== null ? 0 : obj.getId();
    }

    public JobType findById(int id) {
        return jobTypeMapper.selectByPrimaryKey(id);
    }

    public int updateById(JobType obj) {
        return jobTypeMapper.updateByPrimaryKeySelective(obj);
    }

    /**
     * 根据主键删除
     * 只能没有子分类或者没有相应职位的才可以删除，否则删除失败。
     * @param id
     * @return
     */
    public int deleteById(int id) {
        //是否有子分类
        JobTypeExample e = new JobTypeExample();
        e.or().andUpperIdEqualTo(id);
        List<JobType> list = jobTypeMapper.selectByExample(e);
        if (list.size() > 0) {
            return 0;
        }
        //是否有职位，待定


        return jobTypeMapper.deleteByPrimaryKey(id);
    }
}
